package AtomicInteger_9;

import java.util.concurrent.atomic.AtomicInteger;
public class 高级操作_多线程最大值更新 {
    private static AtomicInteger maxValue = new AtomicInteger(0);

    public static void main(String[] args) {
        final int THREAD_COUNT = 20;

        for (int i = 0; i < THREAD_COUNT; i++) {
            final int threadValue = i * 10;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep((long)(Math.random() * 100)); // 模拟处理时间

                        // 使用getAndUpdate原子性更新最大值
                        maxValue.getAndUpdate((current)->{
                            return Math.max(current, threadValue);
                        });

                        System.out.println(Thread.currentThread().getName() +
                                                   " 提交值: " + threadValue + "，当前最大值: " + maxValue.get());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "线程-" + i).start();
        }

        // 等待所有线程完成
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终最大值: " + maxValue.get());
    }
}